package team.scau.laboratory_repair.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.scau.laboratory_repair.common.base.BaseService;
import team.scau.laboratory_repair.common.page.MyPage;
import team.scau.laboratory_repair.modules.po.QRecordSubscription;
import team.scau.laboratory_repair.modules.po.Record;
import team.scau.laboratory_repair.modules.po.RecordSubscription;
import team.scau.laboratory_repair.modules.repository.RecordSubscriptionRepository;

/**
 * @author 30254
 * creadtedate:2018/9/16
 */
@Service
public class RecordSubscriptionService extends BaseService<RecordSubscription, RecordSubscriptionRepository> {

    @Autowired
    RecordSubscriptionRepository recordSubscriptionRepository;

    private QRecordSubscription qRecordSubscription = QRecordSubscription.recordSubscription;

    @Override
    public RecordSubscriptionRepository getRepository() {
        return recordSubscriptionRepository;
    }

    @Override
    public EntityPathBase<RecordSubscription> getQBase() {
        return qRecordSubscription;
    }

    public QueryResults<RecordSubscription> listOrByExample(MyPage page, RecordSubscription recordSubscription) {
        JPAQuery<RecordSubscription> jpaQuery = queryFactory.select(qRecordSubscription).from(qRecordSubscription);
        if (recordSubscription != null) {
            if (recordSubscription.getId() != null) {
                jpaQuery = jpaQuery.where(qRecordSubscription.recordId.eq(recordSubscription.getId()));
            }
        }
        jpaQuery = jpaQuery.where(qRecordSubscription.valid.eq(true));
        if (page != null) {
            jpaQuery = jpaQuery.orderBy(page.getSort()).offset(page.getPage()).limit(page.getSize());
        }
        return jpaQuery.fetchResults();
    }

    public RecordSubscription getByRecordId(Long recordId) {
        JPAQuery<RecordSubscription> jpaQuery = queryFactory.select(qRecordSubscription).from(qRecordSubscription);
        if (recordId != null) {
            jpaQuery = jpaQuery.where(qRecordSubscription.recordId.eq(recordId));
        }
        jpaQuery = jpaQuery.where(qRecordSubscription.valid.eq(true));
        return jpaQuery.fetchOne();
    }
}
